<?php

namespace App\Console\Commands;

use App\Models\ClassBaseInfo;
use App\Models\UserSubscribe;
use App\Services\Admin\UserSubscribeService;
use App\Services\Api\EasyWeChatService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;


class StartClassDetect extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'class:detect';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $new_time = date("Y-m-d H:i:s");

        $where = [];

        $where[] = ['class_time','>=', $new_time];

        $user_result = (new UserSubscribe())->with(['class_base_info'=>function($query){
            $query->select('minimum_number','start_before_minutes','id', 'class_time');
        },'user'=>function($query){
            $query->select('wx_openid','id','user_number');
        }])->where($where)->whereIn('subscribe_status',[2,5])->select('user_id','class_base_info_id','id','class_time','subscribe_status')->get()->toArray();

        $class_deal = [];

        //数据拼接
        foreach ($user_result as $v){

            if(empty($v['class_base_info']['start_before_minutes']))continue;

            //处理时间
            $processing_time = strtotime("{$v['class_time']}") - $v['class_base_info']['start_before_minutes'] * 60;

            $class_key = "{$v['class_base_info_id']}/{$v['class_time']}/{$processing_time}/{$v['class_base_info']['minimum_number']}";

            $input = [];

            $input['user_id'] = $v['user']['id'];

            $input['user_number'] = $v['user']['user_number'];

            $input['wx_openid'] = $v['user']['wx_openid'];

            $input['user_subscribe_id'] = $v['id'];

            $input['subscribe_status'] = $v['subscribe_status'];

            $input['class_base_info'] = json_encode($v['class_base_info']);

            $class_deal[$class_key][] = $input;

        }

        $cancel_user = [];

        //数据处理
        foreach ($class_deal as $k=>$v){
            $key_info = explode('/',$k);

            $processing_time = $key_info[2]??0;

            $minimum_number = $key_info[3]??0;

            if(count($v) < $minimum_number and strtotime($new_time) > $processing_time){

                foreach ($v as $vv) {
                    //用来记录日志
                    $vv['reserve_num'] = count($v);
                    //不够人数开课
                    $cancel_user[] = $vv;
                }

            }
        }

        if(!empty($cancel_user)) {

            $user_subscribe_id = array_column($cancel_user,'user_subscribe_id');

            $user_number = array_column($cancel_user,'user_number');

            $class_base_info = array_column($cancel_user,'class_base_info');

            $reserve_num = array_column($cancel_user,'reserve_num');

            $subscribe_status = array_column($cancel_user,'subscribe_status');

            DB::beginTransaction();
            try {

                //取消预约
                (new UserSubscribe())->whereIn('id', $user_subscribe_id)->update(['subscribe_status'=>'4']);

                //退还积分
                foreach ($user_subscribe_id as $k=>$v){

                    $order = (new UserSubscribe())->where('id',$v)->first();

                    $msg_time_day = date("Y-m-d",strtotime("{$order->class_time}"));

                    $start_class_time_array = date("H:i",strtotime("{$order->class_time}"));

                    $end_class_time_array = date("H:i",strtotime("{$order->end_time}"));

                    $msg_class_time_string = "{$start_class_time_array}-{$end_class_time_array}";

                    $msg_result = [
                        '因人數不足無法開課，退還對應積分以及現金卷',
                        "+{$order->use_integral}分",
                        $msg_time_day,
                        $msg_class_time_string,
                        $order->class_name
                    ];

                    //扣减积分
                    $remark = implode("/",$msg_result);

                    if(!empty($order->user_vip_use_record_id)){
                        UserSubscribeService::appointment_queue_vip_remark($order, '因人數不足無法開課，退還對應vip次数');
                    }else {
                        UserSubscribeService::cancel_return_consumption($order, $remark);
                    }

                    $user_number_value = $user_number[$k]??'';
                    $data = [
                        'character_string1'=>['value'=>$user_number_value],      //会员编号
                        'thing2'=>['value'=>$order->class_name],                      //課程名稱
                        'thing3'=>['value'=>$order->store_name],                      //上课地点
                        'time4'=>['value'=>$order->class_time],                        //日期
                        'thing5'=>['value'=>'因人數不足無法開課'],                         //預約狀態
                    ];

                    EasyWeChatService::sendUserMessage($order->user_id, $data);


                    $log = array(
                        'title' => '系统人数不够取消预约debug日志',
                        'user_subscribe_id' => $v,
                        'class_base_info_id' => $class_base_info[$k]??[],
                        'class_time' => $order->class_time,
                        'reserve_num' => $reserve_num[$k]??0,
                        'subscribe_status' => $subscribe_status[$k]??0,
                        'new_time' => date("Y-m-d h:i:s")
                    );

                    Log::info($log);

                }

                DB::commit();

            } catch (\Exception $e) {
                //接收异常处理并回滚
                DB::rollBack();
            }
        }

    }
}
